/*
 * Copyright 2010 Christian Matzat and others
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package net.matzat.android.hiberdroid.example;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import net.matzat.android.hiberdroid.criteria.Criteria;
import net.matzat.android.hiberdroid.criteria.Restriction;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Locale;

public class EditActivity extends Activity {

    private static final String TAG = EditActivity.class.getSimpleName();

    private Contact contact;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);

        Long contactId = null;
        if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(MainActivity.CONTACT_ID)) {
            contactId = getIntent().getExtras().getLong(MainActivity.CONTACT_ID);
        }
        if (contactId != null) {
            Criteria<Contact> crit = new Criteria<Contact>(Contact.class);
            crit.add(Restriction.idEq(contactId));
            contact = crit.uniqueResult();
            if (contact != null) {
                getTextView(R.id.fullname).setText(contact.getFullName());
                getTextView(R.id.firstname).setText(contact.getFirstname());
                getTextView(R.id.name).setText(contact.getName());
                getTextView(R.id.street).setText(contact.getStreet());
                getTextView(R.id.zip).setText(Integer.toString(contact.getZip()));
                getTextView(R.id.city).setText(contact.getCity());
                getCheckBox(R.id.agreed).setChecked(contact.isAgree());
                if (contact.getBirthDate() != null) {
                    getTextView(R.id.birthDate).setText(DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY).format(contact.getBirthDate()));
                }
            }
        } else {
            contact = new Contact();
        }
        Button save = (Button) findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onSave();
            }
        });

        Button cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onCancel();
            }
        });

    }

    private void onSave() {
        if (getTextView(R.id.fullname).getText() != null) {
            contact.setFullName(getTextView(R.id.fullname).getText().toString());
        }
        if (getTextView(R.id.firstname).getText() != null) {
            contact.setFirstname(getTextView(R.id.firstname).getText().toString());
        }
        if (getTextView(R.id.name).getText() != null) {
            contact.setName(getTextView(R.id.name).getText().toString());
        }
        if (getTextView(R.id.street).getText() != null) {
            contact.setStreet(getTextView(R.id.street).getText().toString());
        }
        if (getTextView(R.id.zip).getText() != null) {
            try {
                contact.setZip(Integer.parseInt(getTextView(R.id.zip).getText().toString()));
            } catch (NumberFormatException e) {
                // zip is malformed
            }
        }
        if (getTextView(R.id.city).getText() != null) {
            contact.setCity(getTextView(R.id.city).getText().toString());
        }
        String birthDate = getTextView(R.id.birthDate).getText().toString();
        if (birthDate != null) {
            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMANY);
            boolean medium = true;
            boolean run = true;
            while (run) {
                try {
                    contact.setBirthDate(dateFormat.parse(birthDate));
                    run=false;
                } catch (ParseException e) {
                    if (medium) {
                        dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMANY);
                        medium = false;
                    } else {
                        run = false;
                    }
                    Log.d(TAG, "Date parsing failed");
                }
            }
        }
        contact.setAgree(getCheckBox(R.id.agreed).isChecked());
        HiberDroidExampleApp.getDB().save(contact);
        finish();
    }

    private void onCancel() {
        finish();
    }

    private TextView getTextView(int id) {
        return (TextView) (findViewById(id));
    }

    private CheckBox getCheckBox(int id) {
        return (CheckBox) (findViewById(id));
    }
}
